import { Form, Drawer, Input, TreeSelect, Select, message, Button } from "antd";
import { FormComponentProps } from "antd/es/form";
import React, { useEffect, useState } from "react";
import { UserItem } from "../data";
import apis from '@/services';

interface Props extends FormComponentProps {
    close: Function;
    save: Function;
    data: Partial<UserItem>;
    
}

interface State {
    confirmDirty: boolean;
    roleList:UserItem[];
    organizationList: any[];
    roleNames:any[];
    tenantName:any[]
}
const Save: React.FC<Props> = props => {

    //随机一个默认密码
    const RandomPassword = (Math.random() * 20).toString();

    const initState: State = {
        confirmDirty: false,
        roleList: [],
        organizationList: [],
        roleNames:[],
        tenantName:[]
    };
    const [confirmDirty, setConfirmDirty] = useState(initState.confirmDirty);
    const [organizationList, setOrganizationList] = useState([]);
    const [roleList, setRoleList] = useState(initState.roleList);
    const [roleNames,setRoleNames] = useState(initState.roleNames);
    const [tenantName,setTenantName] = useState(initState.tenantName);

    const { form: { getFieldDecorator }, form } = props;
   
    const submitData = () => {
        form.validateFields((err, fileValue) => {
            if (err) return;
            if (fileValue.password === RandomPassword) {
                fileValue.password = undefined;
                fileValue.confirm = undefined;
            }
            fileValue.id = props.data.id;
            fileValue.roleNames = props.data.roleNames;
            fileValue.tenantName = props.data.tenantName;
            if (!props.data.id) {
                fileValue.status = 0;
            }
            fileValue.roleNames = roleNames;
            if(fileValue.roleNames.length == 0){
                fileValue.roleNames = props.data.roleNames;
            }
            fileValue.tenantName = tenantName;
            if(fileValue.tenantName == '' || fileValue.tenantName == undefined ){
                fileValue.tenantName = props.data.tenantName;
            }
            // if(fileValue.tenantName.length < 1){
            //     fileValue.tenantName = '';
            // }
            console.log(fileValue)
            props.save(fileValue); 
        });
    };
   
    const handleConfirmBlur = (event: any) => {
        const value = event.target.value;
        setConfirmDirty(confirmDirty || !!value);
    };
    //确认密码判断
    const compareToFirstPassword = (rule, value, callback) => {
        if (value && value !== form.getFieldValue('password')) {
            callback('您输入的两个密码不一致！');
        }else{
            callback();
        }
    };
    //用户密码输入判断
    const validateToNextPassword = (rule, value, callback) => {
        // var pattern = /^(([\x21-\x7e]+)[A-Za-z0-9])+$/;
        var pattern = /^[A-z0-9\x21-\x7e]+$/;
        // var pattern = /^(?![A-z0-9]+$)(?=.[^%&',;=?$\x22])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,20}$/;
        if(!pattern.test(value)){
            callback('密码包含大小写字母、数字、特殊字符！！');
        }else if(value && confirmDirty){
            form.validateFields(['confirm'], { force: true });
        }
        callback();
    };
    const handleChange = (e,obj) =>{
        let idstrList: any = [];
            obj.map((item:any) =>{
                idstrList.push(item.props.children)
            })
            setRoleNames(idstrList)
    };
    const jgChange = (e,obj)=>{
        obj.map((item:any) =>{
            setTenantName(item)
        })
    };

    useEffect(() =>{
        //获取角色下拉框数据
        apis.users.rolelist().then((response: any )=> {
            let list: any = [];
            response.result.map((item:any) => {
                list.push({
                    id:item.id,
                    name:item.name
                })
                setRoleList(list)
            })
            }).catch(() => {
        });
        // 获取机构下拉框数据
        apis.users.getOrganization()
            .then((res: any) => {
            if (res.status === 200) {
                let orgList: any = [];
                res.result.map((item: any) => {
                    orgList.push({ id: item.id, pId: item.parentId, value: item.id, title: item.name })
                });
                setOrganizationList(orgList);
            }
            }).catch(() => {
        });
    }, []);
    return (
        <Drawer
            title={`${props.data.id ? '编辑' : '新建'}用户`}
            visible
            width={800}
            onClose={() => props.close()}
        >
            <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>

                <Form.Item
                    key="name"
                    label="姓名"
                >
                    {getFieldDecorator('name', {
                        rules: [{ required: true, message: '请输入姓名' }],
                        initialValue: props.data.name
                    })(<Input placeholder="请输入" />)}
                </Form.Item>
                {
                    props.data.id ? (<Form.Item
                        key="username"
                        label="用户名"
                    >
                        {getFieldDecorator('username', {
                            initialValue: props.data.username,
                        })(<Input placeholder="请输入" disabled={true} />)}
                    </Form.Item>) : (<Form.Item
                        key="username"
                        label="用户名"
                    >
                        {getFieldDecorator('username', {
                            rules: [{ required: true, message: '请输入用户名' }],
                            initialValue: props.data.username,
                        })(<Input placeholder="请输入" />)}
                    </Form.Item>)
                }
                 <Form.Item
                    key="positionName"
                    label="岗位名称"
                >
                    {getFieldDecorator('positionName', {
                        rules: [{message: '请输入岗位名称' }],
                        initialValue: props.data.positionName
                    })(<Input placeholder="请输入" />)}
                </Form.Item>
                <Form.Item
                    key="phoneNum"
                    label="手机号码"
                >
                    {getFieldDecorator('phoneNum', {
                        rules: [{message: '请输入手机号码' }],
                        initialValue: props.data.phoneNum
                    })(<Input placeholder="请输入" />)}
                </Form.Item>
                <Form.Item
                    key="mailbox"
                    label="邮箱"
                >
                    {getFieldDecorator('mailbox', {
                        rules: [{ message: '请输入邮箱地址' }],
                        initialValue: props.data.mailbox
                    })(<Input placeholder="请输入" />)}
                </Form.Item>
                <Form.Item
                    key="wechatNum"
                    label="微信号"
                >
                    {getFieldDecorator('wechatNum', {
                        rules: [{ message: '请输入微信号' }],
                        initialValue: props.data.wechatNum
                    })(<Input placeholder="请输入" />)}
                </Form.Item>
                <Form.Item key="tenantId" label="所属机构">
                    {getFieldDecorator('tenantId', {
                        initialValue: props.data.tenantId,
                    })(
                        <TreeSelect
                        allowClear treeDataSimpleMode showSearch
                        placeholder="所属机构" treeData={organizationList}
                        treeNodeFilterProp='title' searchPlaceholder='根据机构名称模糊查询'
                        onChange={jgChange}/>
                    )}
                </Form.Item>
                <Form.Item key="roleIds" label="角色名称">
                    {getFieldDecorator('roleIds', {
                        initialValue: props.data.roleIds,
                    })(
                        <Select placeholder="请选择" mode="multiple" onChange={handleChange}>
                        {(roleList || []).map(item => (
                            <Select.Option
                            key={JSON.stringify({ jsId: item.id, jsName: item.name })}
                            value={item.id}
                            >
                            {item.name}
                            </Select.Option>
                        ))}
                        </Select>,
                    )}
                </Form.Item>
                <Form.Item
                    key="password"
                    label="密码"
                >
                    {getFieldDecorator('password', {
                        rules: [
                            { required: true, message: '请输入密码' },
                            {
                                validator: validateToNextPassword,
                            }
                        ],
                        initialValue: props.data.id ? RandomPassword : null
                    })(<Input.Password visibilityToggle={false} />)}
                </Form.Item>
                <Form.Item
                    key="confirm"
                    label="确认密码"
                >
                    {getFieldDecorator('confirm', {
                        rules: [
                            { required: true, message: '请输入重复密码' },
                            {
                                validator: compareToFirstPassword,
                            }
                        ],
                        initialValue: props.data.id ? RandomPassword : null
                    })(
                        <Input.Password
                            visibilityToggle={false}
                            onBlur={(event) => {
                                event.persist();
                                handleConfirmBlur(event)
                            }}
                        />
                    )}
                </Form.Item>
            </Form>
            <div
                style={{
                position: 'absolute',
                right: 0,
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e9e9e9',
                padding: '10px 16px',
                background: '#fff',
                textAlign: 'right',
                }}
            >
                <Button onClick={()=>props.close()} style={{ marginRight: 8 }}>
                取消
                </Button>
                <Button onClick={()=>submitData()} type="primary">
                确定
                </Button>
            </div>
        </Drawer>
    );
};
export default Form.create<Props>()(Save);
